<template>
  <div>
    <h1>英雄列表</h1>
    <el-form @submit.native.prevent>
      <el-form-item label="英雄名称">
        <el-autocomplete
          v-model="query.where.name.$regex"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
        ></el-autocomplete>
        <el-button @click="fetch" type="primary" style="margin-left:10px">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="items" style="width: 100%;">
      <el-table-column prop="_id" label="ID" width="240"></el-table-column>
      <el-table-column prop="name" label="英雄名称"></el-table-column>
      <el-table-column prop="title" label="称号"></el-table-column>
      <el-table-column prop="avatar" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" alt="没有图片" style="height:2.5rem" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="$router.push(`/heroes/edit/${scope.row._id}`)"
          >编辑</el-button>
          <el-button type="text" size="small" @click="remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="page.pageSizes"
      :page-size="page.pageSize"
      :current-page.sync="query.page"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
      page: {
        pageSize: 5,
        pageSizes: [5, 10, 20, 50],
        total: 0
      },
      query: {
        page: 1,
        limit: 5,
        where: {
          name: {
            $regex: ""
          }
        }
      }
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.query.limit = pageSize;
      this.fetch();
    },
    handleCurrentChange() {
      this.fetch();
    },
    async querySearch(queryString, cb) {
      const all = await this.$http.get("rest/heroes", {
        params: { ...this.query, limit: 100,page:1 }
      });
      const result = all.data.data.map(item => ({ value: item.name }));
      cb(result);
    },
    async fetch() {
      const res = await this.$http.get("rest/heroes", {
        params: this.query
      });
      this.items = res.data.data;
      this.page.total = res.data.total;
    },
    async remove(row) {
      this.$confirm(`是否删除英雄 "${row.name}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await this.$http.delete(`rest/heroes/${row._id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.fetch();
      });
    }
  },
  created() {
    this.fetch();
  }
};
</script>

<style></style>
